package bh

import android.content.Context.LOCATION_SERVICE
import android.content.Intent
import android.graphics.drawable.Drawable
import android.graphics.drawable.TransitionDrawable
import android.location.LocationManager
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import androidx.viewpager.widget.ViewPager
import yyee.llee.mmee.base_api_net.base_api_bean.bean.CityBean
import yyee.llee.mmee.common.R
import yyee.llee.mmee.common.databinding.FragmentWeatherBinding
import yyee.llee.mmee.viewmode.WeatherViewModel

class GA : FR<FragmentWeatherBinding>() {

    private var TAG = "GA"

    //区分添加城市回来寻中新加的index
    private var saveCurrentItem = false

    //是否同意隐私
    private var isPrivacy = true

    //避免一只请求权限
    private var isPermission = true


    //避免权限弹框导致onResume一直走
    private var isResume = true

    private val mViewModel by lazy {
        ViewModelProviders.of(requireActivity()).get(WeatherViewModel::class.java)
    }
    private val fragments: MutableList<Fragment> by lazy { ArrayList() }
    private var cityList = mutableListOf<CityBean>()
    private var mCurIndex = 0

    /**
     * 当前的天气code
     */
    private var currentCode = ""
    var addCityListen: FO? = null

    fun initListener(addCityListen: FO) {
        this.addCityListen = addCityListen;
    }

    companion object {

        private var instance: GA? = null

        fun getInstance(): GA {
            if (instance == null) {
                instance = GA()
            }
            return instance!!
        }

        val city = "city"
        val PARAM_CITY = "param_city"

        //添加跳到新添加页面
        const val SAVECURRENTITEM = "saveCurrentItem"

        //存储避免一直请求权限
        const val REQPERMISSION = "reqPermission"
        const val REQUEST_LOCATION_POWER = 1000
    }

    override fun onResume() {
        super.onResume()
        if (isResume) {
            initWeatherData()
        }
    }

    override fun initView(view: FragmentWeatherBinding) {

        viewBinding!!.viewPager.addOnPageChangeListener(object :
            ViewPager.SimpleOnPageChangeListener() {

            override fun onPageSelected(i: Int) {

                bh.FW.setParam(activity, "fragment_position", i)
                //定位城市显示定位图标
                viewBinding!!.ivLoc.visibility =
                    if (cityList[i].isLocal) View.VISIBLE else View.GONE
                viewBinding!!.tvLocation.text = cityList[i].cityName
                //小圆点变灰
                viewBinding!!.llRound.getChildAt(mCurIndex).isEnabled = false
                //小圆点变亮
                viewBinding!!.llRound.getChildAt(i).isEnabled = true
                mCurIndex = i
            }
        })
        //默认背景
        viewBinding!!.ivBg.setImageResource(FU.defaultBg)
        //改变背景
        mViewModel.mCurCondCode.observe(this) {
            changeBg(it)
        }

        if (isPrivacy && isPermission) {
            //检查定位权限 同意隐私并且重新进入才请求
            checkGetLocation()
        }

    }

    private fun initWeatherData() {
        //读取缓存
        val cacheList = bh.FW.getDataList<CityBean>(activity, city)
        if (cacheList.isNullOrEmpty()) {
            //设置默认地区
            val cityBeanSh = CityBean("1", "北京", false)
            cityList.clear()
            cityList.add(cityBeanSh)
            //存储默认
            bh.FW.saveDataList(activity, city, cityList)
        } else {
            //拿到缓存
            cityList.clear()
            cityList.addAll(cacheList)
        }

        showCity()
    }

    /**
     * 显示城市
     */
    private fun showCity() {


        saveCurrentItem =
            bh.FW.getParam(activity, SAVECURRENTITEM, false) as Boolean
        isPermission =
            bh.FW.getParam(activity, REQPERMISSION, true) as Boolean

        if (mCurIndex > cityList.size - 1) {
            mCurIndex = cityList.size - 1
        }
        //显示定位icon和名称
        viewBinding!!.ivLoc.visibility =
            if (cityList[mCurIndex].isLocal) View.VISIBLE else View.GONE
        viewBinding!!.tvLocation.text = cityList[mCurIndex].cityName

        viewBinding!!.llRound.removeAllViews()
        // 宽高参数
        val size = bi.GF.dip2px(activity, 4f)
        val layoutParams = LinearLayout.LayoutParams(size, size)
        // 设置间隔
        layoutParams.rightMargin = 10
        layoutParams.leftMargin = 10
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL

        for (i in cityList.indices) {
            // 创建底部指示器(小圆点)
            val view = View(mContext)
            view.setBackgroundResource(R.drawable.background)
            view.isEnabled = false
            // 添加到LinearLayout
            viewBinding!!.llRound.addView(view, layoutParams)
        }
        // 小白点亮色
        viewBinding!!.llRound.getChildAt(mCurIndex).isEnabled = true
        //如果就一个城市隐藏小圆点
        viewBinding!!.llRound.visibility = if (cityList.size <= 1) View.GONE else View.VISIBLE

        fragments.clear()
        for (city in cityList) {
            //创建城市页面
            val weatherFragment = FZ.newInstance(city)
            fragments.add(weatherFragment)
        }
        viewBinding!!.viewPager.adapter = FY(childFragmentManager, fragments)
        viewBinding!!.viewPager.isSaveEnabled = false
        viewBinding!!.viewPager.offscreenPageLimit = 5

        //区分是否添加跳转过来的
        if (saveCurrentItem) {
            bh.FW.setParam(activity, SAVECURRENTITEM, true)
            viewBinding!!.viewPager.currentItem = fragments.size - 1
        } else {
            viewBinding!!.viewPager.currentItem = mCurIndex
        }

    }

    override fun initListener() {

        viewBinding!!.tvGps.setOnClickListener {
            //点击获取权限拒绝后不能在请求
            isResume = false
            checkGetLocation()
        }

        viewBinding!!.ivAddCity.setOnClickListener {
            startActivity(Intent(activity, DA::class.java))
            addCityListen?.showAd()
        }
        viewBinding!!.settIv.setOnClickListener {
            startActivity(Intent(activity, DD::class.java))
        }
    }


    //定位权限
    private fun checkGetLocation() {
//        FV.requestPermissionFrg(
//            this,
//            arrayListOf(
//                Manifest.permission.ACCESS_FINE_LOCATION,
//                Manifest.permission.ACCESS_COARSE_LOCATION,
//            ),
//            "获取您的位置权限，需要征得您的同意。",
//            mPermissionGrant
//        )
    }

    //权限回调
    private var mPermissionGrant: FV.Companion.PermissionGrant =
        object : FV.Companion.PermissionGrant {
            override fun onPermissionGranted() {
                if (checkGPSOpen()) {//检查gps
                    getLocation()//获取位置
                } else {//去开启
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivityForResult(intent, REQUEST_LOCATION_POWER)
                }
            }

            override fun onPermissionCancel() {
//                viewBinding!!.tvGps.visibility = View.VISIBLE
                bh.FW.setParam(activity, REQPERMISSION, false)
            }
        }

    /**
     * 检查GPS状态
     */
    fun checkGPSOpen(): Boolean {
        val locationManager = activity?.getSystemService(LOCATION_SERVICE) as LocationManager
        val pr1 = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val pr2 = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        return (pr1 || pr2)
    }


    //手动开启gps回到首页重新请求权限
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_LOCATION_POWER -> {
                checkGetLocation()
            }
        }
    }

    //获取位置
    fun getLocation() {
//        AMapLocationClient.updatePrivacyShow(activity, true, true);
//        AMapLocationClient.updatePrivacyAgree(activity, true)
//
//        viewBinding!!.tvGps.visibility = View.VISIBLE
//        viewBinding!!.tvGps.text = ""
//        //初始化定位
//        val mLocationClient = AMapLocationClient(activity)
//        //声明AMapLocationClientOption对象
//        val mLocationOption = AMapLocationClientOption()
//        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
//        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
//        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
//        mLocationOption.interval = 10000
//        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
//        mLocationOption.httpTimeOut = 20000
//        mLocationClient.setLocationListener { aMapLocation ->
//
//
//            if (aMapLocation.errorCode == 0) {
//                //拿到定位
//                viewBinding!!.tvGps.visibility = View.GONE
//                isResume = true
//                upLocationData(aMapLocation)
//            }
//            mLocationClient.onDestroy()
//        }
//        //给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption)
//        //启动定位
//        mLocationClient.startLocation()
    }

//    private fun upLocationData(aMapLocation: AMapLocation) {
//        viewBinding!!.tvGps.visibility = View.GONE
//        //读取缓存
//        val cacheList = FW.getDataList<CityBean>(activity, city)
//
//        val cityList: Citys = Gson().fromJson(
//            AssetsUtils.getJson("hot_city.json", activity),
//            Citys::class.java
//        )
//
//        var areaCode = ""
//        var district = ""
//        for (item in cityList.result!!){
//            if (aMapLocation.district.contains(item.district) &&  aMapLocation.province.contains(item.province)){
//                areaCode = ""+item.id
//                district = item.province
//            }
//        }
//
//        //定位的数据
//        val cityBean = CityBean(
//            areaCode,
//            district,
//            true,
//            (aMapLocation.longitude.toString() + "," + aMapLocation.latitude)
//        )
//        if (!cacheList.isNullOrEmpty()) {
//            //如果有缓存 初始化存默认的了 所以肯定有缓存
//            val it: MutableIterator<CityBean> = cacheList.iterator()
//            while (it.hasNext()) {
//                val next = it.next()
//                //有定位
//                if (next.isLocal) {
//                    //并且和当前定位相等 直接返回
//                    if (aMapLocation.district.contains(next.cityName)) {
//                        break
//                    } else {
//                        //不相等删除 在添加 设置数据
//                        it.remove()
//                        cacheList.add(0, cityBean)
//                        changeViewPager(cacheList)
//                        break
//                    }
//                } else {
//                    //没有定位 删除默认的 定位直接添加到第一个
//                    it.remove()
//                    cacheList.add(0, cityBean)
//                    changeViewPager(cacheList)
//                    break
//                }
//            }
//        }
//    }

    private fun changeViewPager(cacheList: MutableList<CityBean>) {
        cityList.clear()
        cityList.addAll(cacheList)
        bh.FW.saveDataList(activity, city, cityList)
        initWeatherData()
    }


    private fun changeBg(condCode: String) {
        if (currentCode == condCode) {
            return
        }
        currentCode = condCode
        // 获取背景
        val bgDrawable = FU.getBg(requireActivity(), condCode.toInt())

        val originDrawable = viewBinding!!.ivBg.drawable
        val targetDrawable = resources.getDrawable(bgDrawable)
        val transitionDrawable = TransitionDrawable(
            arrayOf<Drawable>(
                originDrawable,
                targetDrawable
            )
        )

        //设置背景
        viewBinding!!.ivBg.setImageResource(bgDrawable)
        transitionDrawable.isCrossFadeEnabled = true
        transitionDrawable.startTransition(100)
    }

}